package com.example.demo.action.server;/**
 * Created by kete on 2018-11-27.
 */

import com.alibaba.fastjson.JSON;
import com.example.demo.action.common.CustomProtocol;
import com.example.demo.action.common.HeartBeatDecode;
import com.example.demo.action.common.NettySocketHolder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.net.InetSocketAddress;

/**
 * 作者：kete
 * 创建时间：2018-11-27 17:30
 * 功能描述：
 * 版本：
 */
@Component
public class HeartBeatServer {

    private final static Logger logger= LoggerFactory.getLogger(HeartBeatServer.class);

    private EventLoopGroup boss = new NioEventLoopGroup();
    private EventLoopGroup work = new NioEventLoopGroup();

    @Value("${netty.server.port}")
    private int nettyPort;

    /**
     * 启动
     */
    @PostConstruct
    public void start() throws Exception{
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(boss,work)
                .channel(NioServerSocketChannel.class)
                .childHandler(new HeartBeatInitChannel())
                .localAddress(new InetSocketAddress(nettyPort))
                .childOption(ChannelOption.SO_KEEPALIVE,true);

        ChannelFuture future = bootstrap.bind().sync();

        if(future.isSuccess()){
            logger.info("server start");
        }
    }

    /**
     * 销毁
     */
    @PreDestroy
    public void destory(){
        boss.shutdownGracefully().syncUninterruptibly();
        work.shutdownGracefully().syncUninterruptibly();
        logger.info("关闭 Netty 成功");
    }

    /**
     * 发送消息
     *
     * @param customProtocol
     */
    public void sendMsg(CustomProtocol customProtocol) {
        NioSocketChannel socketChannel = NettySocketHolder.get(customProtocol.getId());

        if (null == socketChannel) {
            throw new NullPointerException("没有[" + customProtocol.getId() + "]的socketChannel");
        }

        ChannelFuture future = socketChannel.writeAndFlush(Unpooled.copiedBuffer(customProtocol.toString(), CharsetUtil.UTF_8));
        future.addListener((ChannelFutureListener) channelFuture ->
                logger.info("服务端手动发消息成功={}", JSON.toJSONString(customProtocol)));
    }

    class HeartBeatInitChannel extends ChannelInitializer<Channel>{

        @Override
        protected void initChannel(Channel channel) throws Exception {
            channel.pipeline()
                    //五秒没有收到消息 将IdleStateHandler 添加到 ChannelPipeline 中
                    .addLast(new IdleStateHandler(5, 0, 0))
                    .addLast(new HeartBeatDecode())
                    .addLast(new HeartBeatSimpleHandle());
        }
    }
}
